using System;
using System.Linq;
using QAssetBundle;
using UnityEngine;
using QFramework;
using Random = UnityEngine.Random;

namespace XCZProject
{
	/// <summary>
	/// 飞刀技能，控制小刀的移动，碰撞等
	/// </summary>
	public partial class SimpleKnife : ViewController
	{
		void Start()
		{
			// Code Here
		}

		
		private float mCurrentSeconds = 0;

		//public BindableProperty<bool> SuperKnife = new BindableProperty<bool>(true);

		private void Update()
		{
			// 如果小刀数量为0，就不执行
			if (Global.SimpleKnifeCount.Value<=0)
			{
				return;
			}
			mCurrentSeconds += Time.deltaTime;
			//如果时间到了飞刀的间隔时间，就发射飞刀
			if (mCurrentSeconds>=Global.SimpleKnifeDuration.Value)
			{
				mCurrentSeconds = 0;
				if (Player.Default)
				{
					// 获取所有的敌人
					var enemies = FindObjectsByType<Enemy>(FindObjectsInactive.Exclude,FindObjectsSortMode.None)
						.OrderBy(enemy => Player.Default.Distance2D(enemy)) // 根据玩家和敌人的距离进行排序
						//.FirstOrDefault();// 取第一个
						.Take(Global.SimpleKnifeCount.Value+Global.SimpleFlyCount.Value);// 取前N个
					//print("有N把小刀："+Global.SimpleKnifeCount.Value);

					var i = 0;
					foreach (var enemy in enemies)
					{
						if (i<4)
						{
							// 延迟播放音效，让音效和小刀的发射时间错开，产生连续发射的效果
							ActionKit.DelayFrame(11 * i, () =>
								{
									AudioKit.PlaySound(Sfx.KNIFE);
								})
								.StartGlobal();
							i++;
						}
						if (enemy)
						{
							// 如果敌人存在，才创建小刀
							Knife.Instantiate()
								.Position(this.Position())
								.Show()
								.Self(self =>
								{
									var selfCache = self;
									var direction = enemy.NormalizedDirection2DFrom(Player.Default);
									self.transform.up = direction;
									
									var rigidbody2D = self.GetComponent<Rigidbody2D>();
									//var direction = enemy.Position() - Player.Default.Position(); // 计算方向
									rigidbody2D.velocity = direction * 10;
									
									// 初始小刀碰到的敌人数量为0.当碰到敌人数量超过小刀的穿透上限后，才消失
									var attackCount = 0;
									self.OnTriggerEnter2DEvent(collider =>
									{
										var hurtBox = collider.GetComponent<HurtBox>();
										if (hurtBox)
										{
											if (hurtBox.Owner.CompareTag("Enemy"))
											{
												//hurtBox.Owner.GetComponent<IEnemy>().Hurt(Global.SimpleKnifeDamage.Value);
												var damageTimes = Global.SuperKnife.Value ? Random.Range(2,3+1) : 1;
												DamageSystem.CalculateDamage(Global.SimpleKnifeDamage.Value*damageTimes,
													hurtBox.Owner.GetComponent<IEnemy>());

												attackCount++;
												if (attackCount>=Global.SimpleKnifeAttackCount.Value)
												{
													selfCache.DestroyGameObjGracefully();
												}
											}
										}
									}).UnRegisterWhenGameObjectDestroyed(self);

									ActionKit.OnUpdate.Register(() =>
									{
										if (Player.Default)
										{
											if (Player.Default.Distance2D(selfCache)>=20)
											{
												self.DestroyGameObjGracefully();
											}
										}
									}).UnRegisterWhenGameObjectDestroyed(self);
								});
						}
					}
					
				}
				
			}
		}
	}
}
